<template>
  <div class="userlist">
    <div class="userlist-header">
      <div class="userlist-title">用户列表</div>
      <div class="userlist-buttons">
        <el-button
          class="adduser-button"
          type="primary"
          @click="adduserdialog()"
          >新增用户</el-button
        >
      </div>
    </div>
    <div class="userlist-content" style="height: 70%">
      <el-table
        :data="usertableData"
        border
        style="width: 100%; height: 100%; font-size: 12px"
      >
        <el-table-column prop="username" label="用户名" width="80" />
        <el-table-column prop="name" label="真实姓名" width="80" />
        <el-table-column prop="phone" label="电话" width="100" />
        <el-table-column prop="accountsname" label="账号" />
        <el-table-column label="是否是管理员" width="100">
          <template #default="scope">
            <div
              style="display: flex; align-items: center"
              v-if="scope.row.isadmin != 2"
            >
              <el-switch
                v-model="scope.row.isadmin"
                inline-prompt
                :before-change="createBeforeChangeHandler(scope.row)"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </div>
            <div
              style="display: flex; align-items: center"
              v-if="scope.row.isadmin == 2"
            >
              是
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <div class="userbuttons">
              <el-button
                size="small"
                v-if="scope.row.isadmin != 2"
                @click="editaccount(scope.row)"
                >分配账号</el-button
              >
              <el-button
                v-if="scope.row.isadmin != 2"
                size="small"
                type="danger"
                @click="deleteuser(scope.row)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="userlist-footer"></div>

    <el-dialog v-model="changeorderdialogVisible" title="新增用户" width="600">
      <div>
        <el-scrollbar
          style="height: 50vh"
          wrap-class="adduserscro"
          view-class="adduserscro"
        >
          <el-form
            :model="adduserform"
            ref="ruleFormRef"
            :rules="rules"
            label-width="150"
            style="max-width: 400px"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="adduserform.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                type="password"
                show-password
                v-model="adduserform.password"
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="rqpassword">
              <el-input
                type="password"
                show-password
                v-model="adduserform.rqpassword"
              />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="adduserform.name" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="adduserform.phone" />
            </el-form-item>
            <el-form-item label="管理员">
              <el-switch
                v-model="adduserform.isadmin"
                inline-prompt
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeAdduser()">取消</el-button>
          <el-button type="primary" @click="submitAdduser(ruleFormRef)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="editaccountVisible" title="编辑账号" width="600">
      <div>
        <el-scrollbar
          style="height: 50vh"
          wrap-class="addaccountscro"
          view-class="addaccountscro"
        >
          <el-form
            :model="editaccountdata"
            label-width="100"
            style="width: 100%; overflow: hidden"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="editaccountdata.username"
                style="width: 300px; font-size: 13px"
                disabled
              />
            </el-form-item>
            <el-form-item label="绑定账号" prop="username">
              <div>
                <div>
                  <el-input
                    v-model="accountkeyword"
                    style="width: 200px; font-size: 13px"
                    placeholder="输入关键词查询账号"
                  />
                  <el-button style="margin-left: 20px" @click="saveaccountkeyword">查询</el-button>
                </div>

                <div style="width: 100%">
                  <div class="accountgroup">
                    <el-scrollbar height="100%">
                      <el-checkbox-group
                        v-model="checkaccountgroup"
                        @change="changeactiveaccount"
                        class="accountgroup-checkbox"
                        size="small"
                      >
                        <el-checkbox
                          v-for="(item, index) in allaccountdata"
                          :key="index"
                          :label="item.account"
                          :value="item.id"
                          border
                        />
                      </el-checkbox-group>
                    </el-scrollbar>
                  </div>
                </div>

                <div class="bindingaccount">
                  <div style="width: 80px">已绑定账号:</div>
                  <div class="bindingaccount-content">
                    <el-scrollbar height="80px">
                      <span class="bindingaccount-font">{{
                        getbindingaccount()
                      }}</span>
                    </el-scrollbar>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeeditaccount()">取消</el-button>
          <el-button type="primary" @click="submiteditaccount()">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import {
  useSaveApi,
  register,
  setuserIsadmin,
  deleteUser,
} from "@/api/user/index.ts";

import { saveAllAccountlist, setuserAccount } from "@/api/account/index.ts";
import { ElMessage, ElMessageBox } from "element-plus";

import type { ComponentSize, FormInstance, FormRules } from "element-plus";

interface RuleForm {
  username: string;
  password: string;
  rqpassword: string;
  name: string;
  phone: string;
  isadmin: number;
}

const usertableData = ref([]);

const ruleFormRef = ref<FormInstance>();
const changeorderdialogVisible = ref(false);
const adduserform = ref<RuleForm>({
  username: "",
  password: "",
  rqpassword: "",
  name: "",
  phone: "",
  isadmin: 0,
});

const addaccountform = ref({
  accounts: "",
});

const activeuser = ref<any>({});

const editaccountdata = ref({});
const editaccountVisible = ref(false);
const accountkeyword = ref("");
const checkaccountgroup = ref([]);
const allaccountdata = ref([]);
const activeaccountdata = ref([]);

// 确认密码
const validateConfirmPassword = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入确认密码"));
  } else if (value !== adduserform.value.password) {
    callback(new Error("两次密码输入不一致"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules<RuleForm>>({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  rqpassword: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
  name: [{ required: true, message: "请输入项目", trigger: "blur" }],
  phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
});

const getallUser = () => {
  useSaveApi().then((res) => {
    // console.log(res);
    if (res.code == 200) {
      // ElMessage({
      //   message: "用户列表查询成功",
      //   type: "success",
      // });
      usertableData.value = res.data;
    }
  });
};

const adduserdialog = () => {
  // console.log("11");

  changeorderdialogVisible.value = true;
};

// 取消
const closeAdduser = () => {
  changeorderdialogVisible.value = false;
  adduserform.value = {
    username: "",
    password: "",
    rqpassword: "",
    name: "",
    phone: "",
    isadmin: 0,
  };
};

// 新增用户
const submitAdduser = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log(adduserform.value);
      let data = {
        username: adduserform.value.username,
        password: adduserform.value.password,
        name: adduserform.value.name,
        phone: adduserform.value.phone,
        isadmin: adduserform.value.isadmin,
      };
      register(data).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          if (res.msg == "注册成功") {
            ElMessage({
              message: "注册成功",
              type: "success",
              plain: true,
            });
            closeAdduser();
            getallUser();
          } else {
            ElMessage({
              message: res.msg,
              type: "warning",
              plain: true,
            });
          }
        } else {
          ElMessage({
            message: "注册失败",
            type: "error",
            plain: true,
          });
        }
      });
    } else {
      // console.log('error submit!', fields)
    }
  });
};
const createBeforeChangeHandler = (row) => {
  return (newValue) => {
    return changeuserIsadmin(row);
  };
};

// 改变管理员状态
const changeuserIsadmin = (row) => {
  return new Promise((resolve) => {
    let msgstr = "";
    if (row.isadmin == 1) {
      if (activeuser.value.isadmin == 2) {
        msgstr = `是否将 ${row.username} 移除管理员`;
      } else {
        msgstr = "";
      }
    } else {
      msgstr = `是否将 ${row.username} 设为管理员`;
    }
    if (msgstr != "") {
      ElMessageBox.confirm(msgstr, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            userId: row.userId,
            isadmin: row.isadmin == 1 ? 0 : 1,
          };
          setuserIsadmin(data).then((res) => {
            if (res.code == 200) {
              ElMessage({
                type: "success",
                message: "操作成功",
              });
              getallUser();
              return resolve(true);
            } else {
              ElMessage({
                type: "error",
                message: "操作失败",
              });
              return resolve(false);
            }
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消",
          });
          return resolve(false);
        });
    } else {
      ElMessage({
        message: "没有权限移除管理员",
        type: "warning",
      });
      return resolve(false);
    }
  });
};

// 删除用户
const deleteuser = (row) => {
  if (activeuser.value.isadmin == 1 || activeuser.value.isadmin == 2) {
    if (row.isadmin != 1) {
      ElMessageBox.confirm(`是否删除 ${row.username}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            userId: row.userId,
          };
          deleteUser(data).then((res) => {
            if (res.code == 200) {
              ElMessage({
                type: "success",
                message: "删除成功",
              });
              getallUser();
            }
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消",
          });
        });
    } else {
      ElMessage({
        message: "请先移除用户管理员权限",
        type: "warning",
      });
    }
  }
};

// 分配账号按钮
const editaccount = (row) => {
  if (row.isadmin == 1 || row.isadmin == 2) {
    ElMessage({
      message: "管理员无需分配账号",
      type: "warning",
    });
  } else {
    editaccountVisible.value = true;
    editaccountdata.value = row;
    checkaccountgroup.value = [];
    accountkeyword.value = "";
    activeaccountdata.value = []
    
    saveallaccountlist();
  }
};

// 查询全部账号
const saveallaccountlist = () => {
  let data = {
    keyword: accountkeyword.value,
  };
  saveAllAccountlist(data).then((res) => {
    if (res.code == 200) {
      allaccountdata.value = res.data;
      console.log(editaccountdata.value);
      if (editaccountdata.value.accounts != null) {
        checkaccountgroup.value = editaccountdata.value.accounts
          .split(",")
          .map(Number);

        checkaccountgroup.value.forEach((item) => {
          res.data.forEach((item2) => {
            if (item == item2.id) {
              activeaccountdata.value.push(item2);
            }
          });
        });
      }
    }
  });
};

const saveaccountkeyword = () => {
  let data = {
    keyword: accountkeyword.value,
  };
  saveAllAccountlist(data).then((res) => {
    if (res.code == 200) {
      allaccountdata.value = res.data;
    }
  });
}

const getbindingaccount = () => {
  let account = "";
  if (activeaccountdata.value.length > 0) {
    account = activeaccountdata.value.map((item) => item.account).join("，");
  }
  return account;
};

const closeeditaccount = () => {
  editaccountVisible.value = false;
  accountkeyword.value = "";
  checkaccountgroup.value = [];
  activeaccountdata.value = []
};

const changeactiveaccount = (value) => {
  activeaccountdata.value = [];
  value.forEach((item) => {
    allaccountdata.value.forEach((item2) => {
      if (item2.id == item) {
        let exists = activeaccountdata.value.some((item3) => item3.id === item);
        if (!exists) {
          activeaccountdata.value.push(item2);
        }
      }
    });
  });
};

const submiteditaccount = () => {
  console.log(activeaccountdata.value);
  console.log(editaccountdata.value);
  let data = {
    accounts: activeaccountdata.value.map(item => item.id).join(','),
    accountsname: activeaccountdata.value.map(item => item.account).join(','),
    userId: editaccountdata.value.userId
  }
  setuserAccount(data).then((res) => {
    console.log(res);
    if (res.code == 200) {
      ElMessage({
        message: "修改账号分配成功",
        type: "success",
      });
      closeeditaccount()
      getallUser();
    }
    
  })
};

onMounted(() => {
  activeuser.value = JSON.parse(localStorage.getItem("currentUserstr"));
  getallUser();
});
</script>

<style scoped>
.userlist {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.userlist-header {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #dcdfe6;
}
.userlist-title {
  font-size: 16px;
  font-weight: bold;
}
.adduser-button {
  font-size: 12px;
}
.userlist-content {
  padding: 10px 0;
  flex: 1;
}
.userlist-footer {
  height: 40px;
}

.userbuttons {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.accountgroup {
  width: 98%;
  max-height: 220px;
  overflow: hidden;
  /* border: 1px solid red; */
}
.accountgroup-checkbox {
  display: flex;
  flex-wrap: wrap;
}

.bindingaccount {
  display: flex;
  margin-top: 10px;
  /* flex-wrap: wrap; */
}

.bindingaccount-content {
  margin-left: 10px;
  width: 320px;
  flex-wrap: wrap;
}
.bindingaccount-font {
  cursor: pointer;
}
</style>

<style>
.adduserscro {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.accountgroup-checkbox .el-checkbox {
  margin: 8px;
}
.bindingaccount-content .el-scrollbar__view {
  display: flex;
  flex-wrap: wrap;
}
</style>